package com.thoughtworks.android.androsphere.service.c2dm;

import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.log4j.Logger;

public class C2DMServiceThread extends Thread {
    private static final Logger logger = Logger.getLogger(C2DMServiceThread.class);

    private LinkedBlockingQueue<Map<String, String>> queue;
    private C2DMProcessor c2dmProcessor;
    private C2DMServiceHelper helper;

    public C2DMServiceThread(C2DMProcessor c2dmProcessor, C2DMServiceHelper helper) {
        this.c2dmProcessor = c2dmProcessor;
        this.helper = helper;
    }

    @Override
    public void run() {
        logger.debug("C2DM Thread Starts");
        while (true) {
            while (!queue.isEmpty()) {
                logger.debug("Picking Queue Element");
                final Map<String, String> postDataMap = queue.peek();
                final C2DMResponse c2DMResponse = c2dmProcessor.setRequestHeaderAndPostData(postDataMap);
                queue.remove();

                if (c2DMResponse.equals(C2DMResponse.DEFER)) {
                    queue.add(postDataMap);
                }
            }

            helper.delayCurrentThreadBy(10l);
        }
    }

    public void setQueue(LinkedBlockingQueue<Map<String, String>> queue) {
        this.queue = queue;
    }
}
